package com.wsc.wisdomchina.activitity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.Tools.JsonTools;
import com.wsc.wisdomchina.Tools.Tools;
import com.wsc.wisdomchina.activitity.minemodule.BaoMingDetailActivity;
import com.wsc.wisdomchina.callback.ContributorView;
import com.wsc.wisdomchina.constant.Constant;
import com.wsc.wisdomchina.javaBean.RespObj;
import com.wsc.wisdomchina.javaBean.ShakeBean;
import com.wsc.wisdomchina.presenter.ContributorPresenter;
import com.wsc.wisdomchina.view.MarqueeTextView;
import com.wsc.wisdomchina.view.MyCountTimer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class ShakeActivity extends FragmentActivity implements SensorEventListener,ContributorView ,View.OnClickListener{

    private static final String TAG = "ShakeActivity";
    private static final String FLAG = "shake";
    private static final String FRESH_FLAG = "fresh";//每秒刷新
    private static final String RESULT_FLAG = "result";//中奖结果
    private static final String SHAKE_FLAG = "shakedata";//用户数据上传服务器
    private static final int START_SHAKE = 0x1;
    private static final int AGAIN_SHAKE = 0x2;
    private static final int END_SHAKE = 0x3;

    private SensorManager mSensorManager;
    private Sensor mAccelerometerSensor;
    private Vibrator mVibrator;//手机震动
    private SoundPool mSoundPool;//摇一摇音效

    //记录摇动状态
    private boolean isShake = false;
    private boolean isCanConniueShake = true;


    private LinearLayout mTopLayout;
    private LinearLayout mBottomLayout;
    private ImageView mTopLine;
    private ImageView mBottomLine;

    private MyHandler mHandler;
    private int mWeiChatAudio;
    private TextView mCountTv;

    private int mCount = 0;

    private String uid = "";

    private CountDownTimer mTimer ;

    private ContributorPresenter contributorPresenter;

    private Button mAgainButton;

    private ImageView regist_back;
    private TextView tv_headtitle;

    private LinearLayout mRoot;
    private ImageView mClose;
    private ImageView mTitle;
    private ImageView mMiddle;
    private Button mTime;

    private TextView mTip1;
    private TextView mTip2;
    private AnimationDrawable animationDrawable;
    private static final int GO_SERVER = 6;

    private boolean isAlive = false;


    private MarqueeTextView mMarqueeTextView;

    private boolean isNeedStartTimer = false;
    private String mLastResult = "";

    private CountDownTimer mCountTimer;

    private int viewType = 0;

private void startCountDownTimer(){
    if(mCountTimer != null){
        mCountTimer.cancel();
        mCountTimer = null;
    }
    mCountTimer = new CountDownTimer(365*24*60*60*1000,1000) {
        @Override
        public void onTick(long l) {
            Log.i("987654321","timer");
            contributorPresenter.freshShakeData(uid,FRESH_FLAG);
        }

        @Override
        public void onFinish() {

        }
    };
    mCountTimer.start();
}
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置只竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_shake);
        //初始化View
        initView();
        mHandler = new MyHandler(this);
        //初始化SoundPool
        mSoundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
        mWeiChatAudio = mSoundPool.load(this, R.raw.weichat_audio, 1);
        Intent intent = getIntent();
        uid = Tools.getSharedPreferencesStrings(Constant.SharePreferenceUserid,"",this);
        //获取Vibrator震动服务
        mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        //startCountTimer();
        contributorPresenter = new ContributorPresenter(this, this);
        contributorPresenter.freshShakeData(uid,FRESH_FLAG);
    }

    @Override
    protected void onStart() {
        super.onStart();
        startCountDownTimer();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isAlive = true;
        if(isNeedStartTimer){
          startCountTimer();
            mTime.setVisibility(View.VISIBLE);
            isNeedStartTimer = false;
            isCanConniueShake = true;
            //获取 SensorManager 负责管理传感器
            mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
            if (mSensorManager != null) {
                //获取加速度传感器
                mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                if (mAccelerometerSensor != null) {
                    mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_UI);
                }
            }
        }
    }



    private void initView() {
        mCountTv = (TextView) findViewById(R.id.tv_count);
        mTopLayout = (LinearLayout) findViewById(R.id.main_linear_top);
        mBottomLayout = ((LinearLayout) findViewById(R.id.main_linear_bottom));
        mTopLine = (ImageView) findViewById(R.id.main_shake_top_line);
        mBottomLine = (ImageView) findViewById(R.id.main_shake_bottom_line);
        regist_back=(ImageView) findViewById(R.id.regist_back);
        regist_back.setOnClickListener(this);
        tv_headtitle=(TextView) findViewById(R.id.tv_headtitle);
        tv_headtitle.setText("摇一摇");

        mRoot = (LinearLayout) findViewById(R.id.shake_root);
        mAgainButton = (Button) findViewById(R.id.btn_again);

        mClose = (ImageView) findViewById(R.id.iv_close);
        mClose.setOnClickListener(this);
        mTitle = (ImageView) findViewById(R.id.iv_shake_title);
        mMiddle = (ImageView) findViewById(R.id.iv_middle);
        mTime = (Button) findViewById(R.id.btn_time);
        //默认
        mTopLine.setVisibility(View.GONE);
        mBottomLine.setVisibility(View.GONE);
        mTip1 = (TextView) findViewById(R.id.tv_tip1);
        mTip2 = (TextView) findViewById(R.id.tv_tip2);

        mMarqueeTextView = (MarqueeTextView) findViewById(R.id.mar_text);

    }
   private void startCountTimer(){
       mAgainButton.setVisibility(View.INVISIBLE);
       mTime.setVisibility(View.VISIBLE);
       regist_back.setVisibility(View.GONE);
       mTimer = new CountDownTimer(15*1000,1000) {
           @Override
           public void onTick(long millisUntilFinished) {
               int time = (int)millisUntilFinished / 1000;//剩余时间
               mTime.setText(time + "″");
           }

           @Override
           public void onFinish() {
               mTime.setText(0 + "″");
               isCanConniueShake = false;
               contributorPresenter.getShakeResult(uid,RESULT_FLAG);
               regist_back.setVisibility(View.VISIBLE);
           }
       };
       mTimer.start();
   }

   private void startShakeAnimation(){
       mMiddle.setImageResource(R.drawable.shake_animation);
       animationDrawable = (AnimationDrawable) mMiddle.getDrawable();
       animationDrawable.start();
   }
    private void stopShakeAnimation(){
        animationDrawable = (AnimationDrawable) mMiddle.getDrawable();
        animationDrawable.stop();
    }
    private void resetView() {
        viewType = 0;
        mRoot.setBackgroundResource(R.drawable.shake_bg);
        mMiddle.setVisibility(View.VISIBLE);
        mMiddle.setImageResource(R.drawable.shake_middle);
        mTitle.setVisibility(View.VISIBLE);
        mTime.setVisibility(View.INVISIBLE);
        mAgainButton.setVisibility(View.VISIBLE);
        mTip1.setVisibility(View.VISIBLE);
        mTip2.setVisibility(View.VISIBLE);
        mClose.setVisibility(View.INVISIBLE);
    }

    private void successView() {
        viewType = 2;
        mRoot.setBackgroundResource(R.drawable.shake_success_bg);
        mMiddle.setVisibility(View.INVISIBLE);
        mTitle.setVisibility(View.INVISIBLE);
        mTime.setVisibility(View.GONE);
        mAgainButton.setText("本轮活动已结束");
         mAgainButton.setVisibility(View.VISIBLE);
        mTip1.setVisibility(View.INVISIBLE);
        mTip2.setVisibility(View.INVISIBLE);
        mClose.setVisibility(View.VISIBLE);
        regist_back.setVisibility(View.VISIBLE);

    }

    private void failView() {
        viewType = 1;
        mRoot.setBackgroundResource(R.drawable.shake_bg);
        mMiddle.setVisibility(View.VISIBLE);
        mMiddle.setImageResource(R.drawable.shake_failed);
        mTitle.setVisibility(View.INVISIBLE);
        mTime.setVisibility(View.GONE);
        mAgainButton.setText("本轮活动已结束");
        mAgainButton.setVisibility(View.VISIBLE);
        mTip1.setVisibility(View.INVISIBLE);
        mTip2.setVisibility(View.VISIBLE);
        mTip2.setText("请等待进入下一轮活动");
        mClose.setVisibility(View.VISIBLE);
        regist_back.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onPause() {
        // 务必要在pause中注销 mSensorManager
        // 否则会造成界面退出后摇一摇依旧生效的bug
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }
        isAlive = false;
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mCountTimer.cancel();
    }

    ///////////////////////////////////////////////////////////////////////////
    // SensorEventListener回调方法
    ///////////////////////////////////////////////////////////////////////////
    @Override
    public void onSensorChanged(SensorEvent event) {
        int type = event.sensor.getType();
        if(!isCanConniueShake){
         return;
        }
        if (type == Sensor.TYPE_ACCELEROMETER) {
            //获取三个方向值
            float[] values = event.values;
            float x = values[0];
            float y = values[1];
            float z = values[2];

            if ((Math.abs(x) > 27 || Math.abs(y) > 27 || Math
                    .abs(z) > 27) && !isShake) {
                isShake = true;
                mCount++;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCountTv.setText("" + mCount);
                    }
                });
                Log.e("---", "晃悠了" + mCount + "次");
                startShakeAnimation();
                Thread thread = new Thread() {
                    @Override
                    public void run() {


                        super.run();
                        try {
                            Log.d(TAG, "onSensorChanged: 摇动");

                            //开始震动 发出提示音 展示动画效果
                            mHandler.obtainMessage(START_SHAKE).sendToTarget();
                            Thread.sleep(200);
                            //再来一次震动提示
                            //mHandler.obtainMessage(AGAIN_SHAKE).sendToTarget();
                            //Thread.sleep(500);
                            mHandler.obtainMessage(END_SHAKE).sendToTarget();


                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    public void onLoadContributorStart(String flag) {

    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        Log.i("12345678","onLoadContributorSuccess:" + flag);
        if(FLAG.equals(flag)){
/*            int haveNext = -1;
            try {
                JSONObject json = new JSONObject(jsonString);
                haveNext =  json.optInt("rs",haveNext);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(mCount >= SUCCESS_COUNT){
                successView(haveNext);
            }else{
                failView(haveNext);
            }
            resetCount();*/
        }else if (FRESH_FLAG.equals(flag)){
            if(mLastResult.equals(jsonString)){
              return;
            }
            mLastResult = jsonString;
            try {
                JSONObject jsonObj = new JSONObject(jsonString);
                   if("1".equals(jsonObj.optString("startActiveFalg"))){
                       regist_back.setVisibility(View.GONE);
                       if(isAlive){
                           isSended = false;
                           Intent intent = new Intent(ShakeActivity.this,CountDownTimeActivity.class);
                           intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                           startActivity(intent);
                           isNeedStartTimer = true;
                           mCountTimer.cancel();
                           mClose.setVisibility(View.INVISIBLE);
                           resetView();
                           //mTime.setVisibility(View.INVISIBLE);
                       }
                    //开始倒计时
                   }
                   if(viewType == 0){
                       String activeIndex = jsonObj.optString("activeCount");
                       String onlineCpunt = jsonObj.optString("onlineCount");
                       mAgainButton.setText("第" + activeIndex + "轮活动即将开始");
                       mTip1.setText("当前为第" + activeIndex + "轮活动");
                       mTip2.setText(onlineCpunt + "用户正在参与!");
                   }
                StringBuffer sb = new StringBuffer();
                try {
                    JSONArray array = jsonObj.optJSONArray("winningUsers");
                    for(int i=array.length();i>0;i--){
                        String item = array.getString(i-1);
                        sb.append("恭喜用户" + item + "第" + i + "轮获得奖品" ).append("             ");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(TextUtils.isEmpty(sb.toString())){
                           mMarqueeTextView.setVisibility(View.GONE);
                       }else{
                           mMarqueeTextView.setVisibility(View.VISIBLE);
                           mMarqueeTextView.setText("" + sb.toString());
                       }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if(RESULT_FLAG.equals(flag)){
            int rs = -1;
            try {
                JSONObject json = new JSONObject(jsonString);
                rs =  json.optInt("rs",-1);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(rs == 1){
                successView();
            }else{
                failView();
            }
            resetCount();
            startCountDownTimer();

        }else if(SHAKE_FLAG.equals(flag)){
            isSended = true;
        }
        }

/*        if(haveNext == -1){
          finish();
        }*/


    private void resetCount() {
        mCount =0;
    }

    @Override
    public void onLoadContributorComplete(String flag) {

    }

    @Override
    public void onLoadContributorError(String error, String flag) {
        Toast.makeText(this,"数据上传失败：" + error,Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mTimer != null){
          mTimer.cancel();
        }
        if(mCountTimer != null){
            mCountTimer.cancel();
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id){
            case R.id.regist_back:
                 closeSelf();
                break;
            case R.id.iv_close:
                resetView();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        //closeSelf();
    }

    private void closeSelf() {
        finish();
/*        Intent intent = new Intent(this, BaoMingDetailActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("acid", acid);
        startActivity(intent);*/
    }

    private  class MyHandler extends Handler {
        private WeakReference<ShakeActivity> mReference;
        private ShakeActivity mActivity;

        public MyHandler(ShakeActivity activity) {
            mReference = new WeakReference<ShakeActivity>(activity);
            if (mReference != null) {
                mActivity = mReference.get();
            }
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case START_SHAKE:
                    sendShakeData();
                    //This method requires the caller to hold the permission VIBRATE.
                    mActivity.mVibrator.vibrate(100);
                    //发出提示音
                    mActivity.mSoundPool.play(mActivity.mWeiChatAudio, 1, 1, 0, 0, 1);
                    mActivity.mTopLine.setVisibility(View.VISIBLE);
                    mActivity.mBottomLine.setVisibility(View.VISIBLE);
                    mActivity.startAnimation(false);//参数含义: (不是回来) 也就是说两张图片分散开的动画
                    break;
                case AGAIN_SHAKE:
                    mActivity.mVibrator.vibrate(100);
                    break;
                case END_SHAKE:
                    //整体效果结束, 将震动设置为false
                    mActivity.isShake = false;
                    // 展示上下两种图片回来的效果
                    mActivity.startAnimation(true);
                    break;
            }
        }

    }
    private boolean isSended = false;
    private void sendShakeData() {
        if(isSended){
         return;
        }
         contributorPresenter.sendUserShake(uid,SHAKE_FLAG);
    }

    /**
     * 开启 摇一摇动画
     *
     * @param isBack 是否是返回初识状态
     */
    private void startAnimation(boolean isBack) {
        //动画坐标移动的位置的类型是相对自己的
        int type = Animation.RELATIVE_TO_SELF;

        float topFromY;
        float topToY;
        float bottomFromY;
        float bottomToY;
        if (isBack) {
            topFromY = -0.5f;
            topToY = 0;
            bottomFromY = 0.5f;
            bottomToY = 0;
        } else {
            topFromY = 0;
            topToY = -0.5f;
            bottomFromY = 0;
            bottomToY = 0.5f;
        }

        //上面图片的动画效果
        TranslateAnimation topAnim = new TranslateAnimation(
                type, 0, type, 0, type, topFromY, type, topToY
        );
        topAnim.setDuration(200);
        //动画终止时停留在最后一帧~不然会回到没有执行之前的状态
        topAnim.setFillAfter(true);

        //底部的动画效果
        TranslateAnimation bottomAnim = new TranslateAnimation(
                type, 0, type, 0, type, bottomFromY, type, bottomToY
        );
        bottomAnim.setDuration(200);
        bottomAnim.setFillAfter(true);

        //大家一定不要忘记, 当要回来时, 我们中间的两根线需要GONE掉
        if (isBack) {
            bottomAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    //当动画结束后 , 将中间两条线GONE掉, 不让其占位
                    mTopLine.setVisibility(View.GONE);
                    mBottomLine.setVisibility(View.GONE);
                }
            });
        }
        //设置动画
        mTopLayout.startAnimation(topAnim);
        mBottomLayout.startAnimation(bottomAnim);

    }


}
